<template>
  <div>
    <div class="item">
      <div class="header">
        <span>描述</span>
      </div>
      <div class="content">
        <a-input
          v-model:value="props.nodeData.properties.remarks"
          :rows="3"
          placeholder="请输入描述"
          style="width: 100%"
          @change="setProperties()"
        />
      </div>
    </div>

    <div class="item">
      <div class="header">
        <span>查询变量</span>
      </div>
      <div class="content">
        <div class="var-item" >
          <div class="field">
            <a-select style="width: 100%"  v-model:value="inputParamId" placeholder="请选择输入字段" @change="handleFieldChange">
              <a-select-option v-for="preItem in prevVariables" :key="preItem.id" :value="preItem.id">
                {{ preItem.nodeName }}/{{ preItem.name }}
              </a-select-option>
            </a-select>
          </div>
        </div>
      </div>
    </div>
    <div class="item">
      <div class="header">
        <span>知识库</span>
        <!-- <a-button type="primary">添加</a-button> -->
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span style="color: #1890ff; cursor: pointer; margin-right: 5px" @click="addKnowledge">添加</span>
            <a-popover placement="topLeft" :overlayStyle="{ width: '380px' }">
            <template #content>
              <a-form ref="userFormRef" class="user-form">
                <a-form-item label="Top K" name="name">
                  <a-row>
                    <a-col :span="16">
                      <a-slider v-model:value="props.nodeData.properties.options.topNumber" :step="1" :min="1" :max="10" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="props.nodeData.properties.options.topNumber" :min="1" :max="10" />
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item label="Score 阈值" name="modelType">
                  <a-row>
                    <a-col :span="16">
                      <a-slider v-model:value="props.nodeData.properties.options.similarity" :step="0.1" :min="0" :max="1" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="props.nodeData.properties.options.similarity" :min="0" :max="1" />
                    </a-col>
                  </a-row>
                </a-form-item>
              
              </a-form>
            </template>
            <icon-font iconClass="icon-opt-shezhi" color="#60666b" font-size="22px" />
          </a-popover>
        </div>
      </div>
      <div class="content">
        <a-row>
          <a-col span="12" v-for="(item,index) in selectKnowledgeList">
            <a-card class="ant-card-hoverable knowledge-card">
              <div style="display: flex; width: 100%; justify-content: space-between; align-items: center">
                <div>
                  <img class="knowledge-img" src="https://boot3.jeecg.com/assets/knowledge-C_-Hx-39.png" />
                  <span class="knowledge-name">{{ item.name }}</span>
                </div>
                <CloseOutlined class="hover-content" @click="deleteItem(index)" />
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
    <div class="item">
      <div class="header">
        <span>输出变量</span>
      </div>
      <div class="content">
        <div style="display: flex; flex-direction: column">
          <span v-for="item in props.nodeData.properties.outputParams" class="ai-label">
            {{ item.field }}&#60;{{ item.type }}&#62;{{ item.name }}
          </span>
        </div>
      </div>
    </div>
  </div>
  <a-modal
    :visible="visible"
    :confirm-loading="loading"
    :forceRender="true"
    title="添加关联知识库"
    @update:visible="updateVisible"
    @ok="save"
    class="common-modal"
    @close="updateVisible(false)"
  >
    <div>
      <a-row>
        <a-col span="12">
          <a-input
            :span="12"
            placeholder="请输入知识库名称,回车搜索"
            v-model:value="queryParam.name"
            @pressEnter="searchKnowledge"
          ></a-input>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12" v-for="item in knowledgeList">
          <a-card class="ant-card-hoverable knowledge-card">
            <div style="display: flex; width: 100%; justify-content: space-between; align-items: center">
              <div>
                <img class="knowledge-img" src="https://boot3.jeecg.com/assets/knowledge-C_-Hx-39.png" />
                <span class="knowledge-name">{{ item.name }}</span>
              </div>
              <a-checkbox v-model:checked="item.checked"></a-checkbox>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue';
import { getPreNodes } from '../../../../utils/flowNodeUtils';
import { KnowledgeApi } from '@/views/super/airag/aiknowledge/api/KnowledgeApi';
const props = defineProps({
  nodeData: Object,
  lf: Object || String
});
const visible = ref(false);

// Computed property to safely get/set inputParams[0].id
const inputParamId = computed({
  get() {
    return props.nodeData.properties.inputParams &&
      props.nodeData.properties.inputParams.length > 0
      ? props.nodeData.properties.inputParams[0].id
      : null;
  },
  set(val) {
   if(props.nodeData.properties.inputParams.length==0)
   {
    props.nodeData.properties.inputParams.push({id:''});

   }
   props.nodeData.properties.inputParams[0].id = val;
      
    
  }
});

const queryParam = reactive({});
const selectKnowledgeList = ref([]);

const knowledgeList = ref([]);

const prevNodes = ref([]);
const prevVariables = computed(() => {
  if (prevNodes.value.length === 0) return [];

  return prevNodes.value.flatMap(prevNode => {
    // 开始节点使用inputParams，其他节点使用outputParams
    const params = prevNode.type === 'start' ? prevNode.properties.inputParams : prevNode.properties.outputParams;

    var dd =
      Array.isArray(params) && params.length > 0
        ? params.map(param => ({
            nodeId: prevNode.id,
            nodeName: prevNode.properties.text,
            field: param.field,
            name: param.name,
            type: param.type,
            id: prevNode.id + '_' + param.field
          }))
        : [];
        console.log("dd");
    console.log(dd);
    return dd;
  });
});
const getSelectKnowledgeList = () => {
  let params = {
    pageNo: 0,
    pageSize: 1000,
    column: 'createTime',
    order: 'desc'
  };
  KnowledgeApi.list(params).then(res => {
    if (res.success) {
      const idSet = new Set(props.nodeData.properties.options.knowIds);
      selectKnowledgeList.value = res.data.records.filter(item => idSet.has(String(item.id)));
    } else {
      selectKnowledgeList.value = [];
    }
  });
};
const getKnowledgeList = () => {
  let params = {
    pageNo: 0,
    pageSize: 1000,
    column: 'createTime',
    order: 'desc'
  };
  Object.assign(params, queryParam);
  KnowledgeApi.list(params).then(res => {
    if (res.success) {
      const idSet = new Set(props.nodeData.properties.options.knowIds);
      res.data.records.forEach(item => {
        item.checked = idSet.has(String(item.id));
      });

      knowledgeList.value = res.data.records;
    } else {
      knowledgeList.value = [];
    }
  });
};
watch(
  () => props.nodeData,
  nodeDataChange => {

    var nodes = getPreNodes(props.nodeData, props.lf.graphModel);
    prevNodes.value = nodes;
        console.log(prevNodes);
    getSelectKnowledgeList();
  },
  {
    immediate: true
  }
);

const handleFieldChange = value => {

  setProperties();
};

const handleModelChange = value => {
  var m = modelList.value.find(item => item.id == value);
  if (m) {
    model.value.params.model = m.name;
    // if (
    //   props.nodeData &&
    //   props.nodeData.properties &&
    //   props.nodeData.properties.options &&
    //   props.nodeData.properties.options.model
    // ) {
    //   props.nodeData.properties.options.model.modeId = value;
    //   props.nodeData.properties.options.model.params = model.params;
    // }
    console.log(props.nodeData.properties);
    setProperties();
  }
};
const inputParams = computed(() => {
  props.nodeData.properties.inputParams.forEach(item => {
    if (item.nodeId) {
      item.id = item.nodeId + '_' + item.field;
    }
  });
  return props.nodeData.properties.inputParams;
});
const getOutputText = computed(() => {
  return (
    props.nodeData.properties.outputParams[0].field +
    '<' +
    props.nodeData.properties.outputParams[0].type +
    '>' +
    props.nodeData.properties.outputParams[0].name
  );
});
const addKnowledge = () => {
  visible.value = true;
  getKnowledgeList();
};
const deleteItem = index => {

selectKnowledgeList.value.splice(index,1);
  props.nodeData.properties.options.knowIds = selectKnowledgeList.value.map(item => item.id);

  setProperties();
};
const updateVisible = value => {
  visible.value = value;
};
const save = () => {
  visible.value = false;
  selectKnowledgeList.value = knowledgeList.value.filter(item => item.checked);
  props.nodeData.properties.options.knowIds = knowledgeList.value.filter(item => item.checked).map(item => item.id);
  setProperties();
};
const searchKnowledge = () => {
  getKnowledgeList();
};
const setProperties = () => {
  props.nodeData.properties.inputParams.forEach(item => {
    // if (item.nodeId) {
    //   item.id = item.nodeId + '_' + item.field;
    // }
    if (item.id) {
      var items = item.id.split('_');
      item.field = items[1];
      item.nodeId = items[0];
    }
  });
  props.lf.setProperties(props.nodeData.id, props.nodeData.properties);
};
</script>

<style lang='less' scoped>
.item {
  padding-top: 4px;
  padding-bottom: 4px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 4px;
    padding: 2px;
    margin-bottom: 8px;
  }
  .content {
    background-color: #fff;
  }
}

.knowledge-card {
  margin-bottom: 10px;
  margin-right: 10px;
}
.knowledge-img {
  width: 30px;
  height: 30px;
}
.knowledge-name {
  margin-left: 4px;
}
.hover-content {
  display: none; /* 默认不显示 */
}

.knowledge-card:hover .hover-content {
  display: block; /* 鼠标悬浮时显示 */
}
</style>